package com.base.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Redicache工具类
 *
 * @author junw
 */
@Component
public class RedisServer {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private final RedisTemplate redisTemplate;

    @Autowired
    public RedisServer(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 批量删除对应的value
     *
     * @param keys 键
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    /**
     * 批量删除key
     *
     * @param pattern 模式
     */
    public void removePattern(final String pattern) {
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0) {
            redisTemplate.delete(keys);
        }
    }

    /**
     * 删除对应的value
     *
     * @param key 键
     */
    private void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }

    /**
     * 判断缓存中是否有对应的value
     *
     * @param key 键
     * @return boolean
     */
    private boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 读取缓存
     *
     * @param key 键
     * @return String
     */
    public String get(final String key) {
        Object result;
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        if (result == null) {
            return null;
        }
        return result.toString();
    }

    /**
     * 写入缓存
     *
     * @param key   键
     * @param value 值
     * @return boolean
     */
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            logger.error("Redis异常：" + e.getMessage());
        }
        return result;
    }

    /**
     * 判断KEY是否存在
     *
     * @param key
     * @return 是否存在
     */
    public boolean exist(String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 写入缓存
     *
     * @param key   键
     * @param value 值
     * @return boolean
     */
    public boolean set(final String key, Object value, Long expireTime) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            logger.error("Redis异常：" + e.getMessage());
        }
        return result;
    }

    /**
     * 写入Map类型数据
     *
     * @param key   键
     * @param value 值
     * @return boolean
     */
    public boolean hmset(String key, Map<String, String> value) {
        boolean result = false;
        try {
            redisTemplate.opsForHash().putAll(key, value);
            result = true;
        } catch (Exception e) {
            logger.error("Redis异常：" + e.getMessage());
        }
        return result;
    }

    /**
     * 获取Map类型数据
     *
     * @param key 键
     * @return Map<String                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               ,                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               String>
     */
    public Map<String, String> hmget(String key) {
        Map<String, String> result = null;
        try {
            result = redisTemplate.opsForHash().entries(key);
        } catch (Exception e) {
            logger.error("Redis异常：" + e.getMessage());
        }
        return result;
    }

    /**
     * 将一个或多个值插入到列表头部
     *
     * @param key   键
     * @param value 值
     * @return 当前列表长度
     */
    public Long lpush(String key, Object... value) {
        Long result = null;
        try {
            result = redisTemplate.opsForList().leftPushAll(key, value);
        } catch (Exception e) {
            logger.error("Redis异常：" + e.getMessage());
        }
        return result;
    }

    /**
     * 将一个或多个值插入到列表尾部
     *
     * @param key   键
     * @param value 值
     * @return 当前列表长度
     */
    public Long rpush(String key, Object... value) {
        Long result = null;
        try {
            result = redisTemplate.opsForList().rightPushAll(key, value);
        } catch (Exception e) {
            logger.error("Redis异常：" + e.getMessage());
        }
        return result;
    }

    /**
     * 弹出sourceListKey末尾的元素插入到destinationListKey的头部，并返回该弹出元素
     *
     * @param sourceListKey      从这里弹出
     * @param destinationListKey 向这里插入
     * @return 弹出元素
     */
    public synchronized Object brpoplpush(String sourceListKey, String destinationListKey) {
        Object result = null;
        try {
            result = redisTemplate.opsForList().rightPopAndLeftPush(sourceListKey, destinationListKey);
        } catch (Exception e) {
            logger.error("Redis异常：" + e.getMessage());
        }
        return result;
    }

    /**
     * 获取列表长度
     *
     * @param listKey 列表键
     * @return 列表长度
     */
    public Long listSize(String listKey) {
        Long result = 0L;
        try {
            result = redisTemplate.opsForList().size(listKey);
        } catch (Exception e) {
            logger.error("Redis异常：" + e.getMessage());
        }
        return result;
    }

    /**
     * 删除key列表里第count次出现的value
     *
     * @param key 键
     * @param count 第几次
     * @param value 值
     * @return 删除的个数
     */
    public Long removeListValue(String key, long count, Object value){
        Long result = null;
        try {
            result = redisTemplate.opsForList().remove(key, count, value);
        } catch (Exception e) {
            logger.error("Redis异常：" + e.getMessage());
        }
        return result;
    }
}
